﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Risk.Model
{
    public class Army : UniqueId
    {
        public Player Player { get; set; }
        public List<Troop> TroopGroup { get; set; }
        public int Reserve { get; set; }
        public int Bonus { get
        {
            //de continenten waarvan de speler op zijn minst 1 gebied heeft
            var continents =
                TroopGroup.GroupBy(t => t.Region.Continent)
                          .Select(g => g.First().Region.Continent)
                          .ToList();
            int sum = 0;
            foreach (var c in continents)
            {
                int nrOfTroopgroupsInContinent = TroopGroup.Count(t => t.Region.Continent == c);
                if (c.Regions.Count == nrOfTroopgroupsInContinent)
                    sum += c.ExtraTroopsForSingleRuler;
            }
            int bonus = TroopGroup.Count/3 + sum;
            return bonus < 3 ? 3 : bonus;
        } }
        public Army(Player p)
        {
            Player = p;
            TroopGroup = new List<Troop>();

        }
        public Army(Player p, int id, int reserve) : this(p)
        {
            Id = id;
            Reserve = reserve;
        }
        public void AddReinforcements()
        {
            Reserve += Bonus;
        }
        public bool PlaceInitialTroops(int playerRiskId, string regionId)
        {
            var targetTroopGroup = TroopGroup.Find(t => t.Region.Id == regionId);
            if (targetTroopGroup == null)
                return false;
            targetTroopGroup.AddTroopsFromReserve(Reserve);
            Reserve = 0;
            return true;
        }
        public Boolean AddTroop(string region)
        {
            if (Reserve == 0)
                return false;
            var targetTroopGroup = TroopGroup.Find(t => t.Region.Id == region);
            if (targetTroopGroup == null)
                return false;
            targetTroopGroup.AddTroop();
            Reserve -= 1;
            return true;
        }

        public bool HasRegion(string regionId)
        {
            return TroopGroup.Any(t => t.Region.Id == regionId);
        }

        public bool HasTroop(Troop troop)
        {
            return TroopGroup.Contains(troop);
        }
    }
}
